package com.app.newcsc.fragment.orderdetail;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;

import com.app.newcsc.BR;
import com.app.newcsc.R;
import com.app.newcsc.app.AppViewModelFactory;
import com.app.newcsc.app.Constants;
import com.app.newcsc.databinding.FragmentOrderDetailUploadBinding;
import com.app.newcsc.entity.TransactionOrderEntity;
import com.app.newcsc.entity.UploadFileEntity;
import com.app.newcsc.utils.GlideUtils;
import com.app.newcsc.utils.TextUtil;
import com.app.newcsc.utils.ToastUtil;
import com.app.newcsc.view.InputPwdDialog;
import com.lwkandroid.imagepicker.ImagePicker;
import com.lwkandroid.imagepicker.data.ImageBean;
import com.lwkandroid.imagepicker.data.ImageContants;
import com.lwkandroid.imagepicker.data.ImagePickType;
import com.lwkandroid.imagepicker.ui.grid.view.ImageDataActivity;
import com.lwkandroid.imagepicker.utils.GlideImagePickerDisplayer;
import com.tbruyelle.rxpermissions2.Permission;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.util.List;

import io.reactivex.functions.Consumer;
import me.goldze.mvvmhabit.base.BaseFragment;

/**
 * @author: woking
 * @date: 2021/6/17
 * @description：
 */
public class OrderDetailUploadFragment extends BaseFragment<FragmentOrderDetailUploadBinding, OrderDetailViewModel> {

    private TransactionOrderEntity mOrderDetailEntity;
    private String wxtype_select = "";
    private UploadFileEntity uploadFileEntity;

    private boolean isZhongCai = false;
    @Override
    public int initContentView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return R.layout.fragment_order_detail_upload;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }
    @Override
    public OrderDetailViewModel initViewModel() {
        //使用自定义的ViewModelFactory来创建ViewModel，如果不重写该方法，则默认会调用NetWorkViewModel(@NonNull Application application)构造方法
        AppViewModelFactory factory = AppViewModelFactory.getInstance(getActivity().getApplication());
        return ViewModelProviders.of(this, factory).get(OrderDetailViewModel.class);
    }
    @Override
    public void initData() {
        super.initData();

        if (getArguments() != null) {
            mOrderDetailEntity = (TransactionOrderEntity)getArguments().getSerializable("entity");
            String title = getArguments().getString("title","上传截图");
            binding.tvTitleText.setText(title);
            if(title.contains("仲裁"))
            {
                isZhongCai = true;
            }
        }

        binding.ivTitleBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getActivity().finish();
            }
        });
        binding.addImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                selectPictur();
            }
        });
        binding.img.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                selectPictur();
            }
        });

        binding.llBank.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                wxtype_select = "1";
                binding.mcbBank.setChecked(true);
                binding.mcbZfb.setChecked(false);
                binding.mcbWx.setChecked(false);
            }
        });
        binding.llZfb.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                wxtype_select = "2";
                binding.mcbBank.setChecked(false);
                binding.mcbZfb.setChecked(true);
                binding.mcbWx.setChecked(false);
            }
        });
        binding.llWx.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                wxtype_select = "3";
                binding.mcbBank.setChecked(false);
                binding.mcbZfb.setChecked(false);
                binding.mcbWx.setChecked(true);
            }
        });
        binding.tvDuihuan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(uploadFileEntity == null || TextUtil.isEmpty(uploadFileEntity.path))
                {
                    ToastUtil.showToast("请上传付款截图");
                    return;
                }
                if(isZhongCai)
                {
                    if(TextUtil.isEmpty(binding.contentTv.getText().toString()))
                    {
                        ToastUtil.showToast("请输入您的问题");
                        return;
                    }
//                    Log.e("TAG","=========uploadFileEntity=============="+uploadFileEntity.path);
                    viewModel.otcBuyAppeal(mOrderDetailEntity.id+"" ,uploadFileEntity.path,binding.contentTv.getText().toString());
                }
                else
                {
                    if(TextUtil.isEmpty(wxtype_select))
                    {
                        ToastUtil.showToast("请选择付款方式");
                        return;
                    }

                    getMemberBaseInfo();
                }
            }
        });
        if(isZhongCai)
        {
            binding.llBank.setVisibility(View.GONE);
            binding.llZfb.setVisibility(View.GONE);
            binding.llWx.setVisibility(View.GONE);
            binding.contentTv.setVisibility(View.VISIBLE);
        }
        else
        {
            setSellerPay(mOrderDetailEntity);
        }

        viewModel.mUploadFileEntity.observe(this, new Observer<UploadFileEntity>() {
            @Override
            public void onChanged(UploadFileEntity entity) {
                if(entity != null)
                {
//                    Log.e("TAG","=======uploadFileEntity==entity=======111111======="+entity.path);
                    uploadFileEntity = entity;
                    GlideUtils.getInstances().loadNormalImg(getActivity(),binding.img,entity.url);
                }
            }
        });
    }

    public TransactionOrderEntity.SellerPay getSellerPay(TransactionOrderEntity entity,String type)
    {
        if(entity != null && entity.sellerPays != null && entity.sellerPays.data.size() > 0)
        {
            for(int i = 0; i < entity.sellerPays.data.size(); i++)
            {
                TransactionOrderEntity.SellerPay data = entity.sellerPays.data.get(i);
                if(Integer.parseInt(type) == data.type)
                {
                    return data;
                }
            }
        }
        return null;
    }

    public void setSellerPay(TransactionOrderEntity entity)
    {
        if(entity != null && entity.sellerPays != null && entity.sellerPays.data.size() > 0)
        {
            String payTypes = "";
            if(entity.pay_types != null && entity.pay_types.size() > 0)
            {
                for(String paytype : entity.pay_types)
                {
//                    Log.e("TAG","============payTypes==========00000====="+paytype);
                    payTypes = payTypes + paytype;
                }
            }
//            Log.e("TAG","============payTypes==============="+payTypes);

            binding.llBank.setVisibility(View.GONE);
            binding.llZfb.setVisibility(View.GONE);
            binding.llWx.setVisibility(View.GONE);
            for(int i = 0; i < entity.sellerPays.data.size(); i++)
            {
                TransactionOrderEntity.SellerPay data = entity.sellerPays.data.get(i);
                if(payTypes.contains(data.type+""))
                {
                    if(1 == data.type)
                    {
                        binding.llBank.setVisibility(View.VISIBLE);
                    }
                    else if(2 == data.type)
                    {
                        binding.llZfb.setVisibility(View.VISIBLE);
                    }
                    else if(3 == data.type)
                    {
                        binding.llWx.setVisibility(View.VISIBLE);
                    }
                }
            }
        }
    }

    private InputPwdDialog inputPasswordDialog;
    private void getMemberBaseInfo() {
        if(mOrderDetailEntity == null)
        {
            return;
        }
        inputPasswordDialog = new InputPwdDialog(getContext(), new InputPwdDialog.InputPasswordListener() {
            @Override
            public void callbackPassword(String password) {
//                Log.e("TAG","====states====callbackPassword=====password=="+password);
                TransactionOrderEntity.SellerPay sellerPay = getSellerPay(mOrderDetailEntity,wxtype_select);
                if(sellerPay != null)
                {
                    viewModel.otcBuySubmit(mOrderDetailEntity.id+"" ,sellerPay.id+"",uploadFileEntity.path, password);
                }
            }
        });
        inputPasswordDialog.setOnDismissListener(dialog -> {

        });
        inputPasswordDialog.show();
    }

    private int code;
    public void selectPictur()
    {
        code = Constants.INTENT_REQUESTCODE_VERIFIED_IMG1;
//        closeKeyBoard();
        new RxPermissions(this).requestEach(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA)
                .subscribe(new Consumer<Permission>() {
                    @Override
                    public void accept(Permission permission) throws Exception {
                        if (permission.granted && Manifest.permission.CAMERA.equals(permission.name)) {
                            // 用户已经同意该权限
                            ImagePicker imagePicker = new ImagePicker()
                                    .pickType(ImagePickType.SINGLE)//设置选取类型(拍照、单选、多选)
                                    .maxNum(1)//设置最大选择数量(拍照和单选都是1，修改后也无效)
                                    .needCamera(true)//是否需要在界面中显示相机入口(类似微信)
                                    .displayer(new GlideImagePickerDisplayer())//自定义图片加载器，默认是Glide实现的,可自定义图片加载器
                                    // .doCrop(1, 1, 300, 300)
                                    ;
                            //.start(AddWXFragment.this, code);

                            Intent intent = new Intent(getActivity(), ImageDataActivity.class);
                            intent.putExtra(ImageContants.INTENT_KEY_OPTIONS, imagePicker.getOptions());
                            startActivityForResult(intent, code);
                        }
                    }
                });
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
//        Log.e("TAG","==========imageUrl========1111======");
        if (resultCode == Activity.RESULT_OK && data != null) {
            List<ImageBean> resultList = data.getExtras().getParcelableArrayList(ImagePicker.INTENT_RESULT_DATA);
            String imageUrl = "";
            if (resultList != null && resultList.size() > 0) {
                imageUrl = resultList.get(0).getImagePath();
//                Log.e("TAG","==========imageUrl=============="+imageUrl);

//                GlideUtils.getInstances().loadNormalImg(getActivity(),binding.img,imageUrl);
//                binding.addImg.setVisibility(View.GONE);

                viewModel.uploadFiles(imageUrl);
            }
            if (requestCode == Constants.INTENT_REQUESTCODE_VERIFIED_IMG1) {
//                uploadImg(imageUrl, 1);
            }

        }
    }
}